//
//  AppContext.m
//  YiJuZhangShou
//
//  Created by 冷悦 on 16/3/3.
//  Copyright © 2016年 Uranus. All rights reserved.
//

#import "AppContext.h"
#import "AppVersion.h"
#import "NetworkingHeader.h"

@implementation AppContext

static AppContext *_instance = nil;

+ (instancetype)sharedInstance {
    static dispatch_once_t onceToken;
    
    dispatch_once(&onceToken, ^{
        _instance = [[AppContext alloc]init];
        [_instance setupDeviceInfos];
        [_instance setupNetworkingMonitor];
        [_instance setupUserId];
        [_instance setupAppToken];
    });
    
    return _instance;
}

#pragma mark - Private
- (void)setupNetworkingMonitor{
    AFNetworkReachabilityManager *manager = [AFNetworkReachabilityManager sharedManager];
    
    __weak typeof(self) weakSelf = self;
    
    [manager setReachabilityStatusChangeBlock:^(AFNetworkReachabilityStatus status) {
        weakSelf.networkingStatus = status;
    }];
    
    [manager startMonitoring];
}

- (void)setupDeviceInfos{
    self.systemName = [[UIDevice currentDevice] systemName];
    self.systemVersion = [[UIDevice currentDevice] systemVersion];
    self.model = [[UIDevice currentDevice] model];
    self.uniqueIdentifier = [[UIDevice currentDevice] identifierForVendor];
    self.name = [[UIDevice currentDevice] name];
    self.localizedModel = [[UIDevice currentDevice] localizedModel];
}

- (void)setupUserId{
    NSNumber *userNum = [[NSUserDefaults standardUserDefaults] objectForKey:@"userId"];
    
    if (userNum != nil) {
        _userId = [userNum integerValue];
    }
}

- (void)setupAppToken{
    NSString *appToken = [[NSUserDefaults standardUserDefaults] objectForKey:@"appToken"];
    _appToken = appToken;
}

#pragma mark Getters
- (NSString *)appVersion{
    return kAppVersion;
}

- (NSString *)baseUrl{
    return _baseUrl == nil ? kBaseUrl : _baseUrl;
}

#pragma mark Setters
- (void)setUserId:(NSInteger)userId{
    if (_userId != userId) {
        _userId = userId;
        NSNumber *userNum = [NSNumber numberWithInteger:userId];
        [[NSUserDefaults standardUserDefaults] setObject:userNum forKey:@"userId"];
    }
}

- (void)setNetworkingStatus:(AFNetworkReachabilityStatus)networkingStatus{
    _networkingStatus = networkingStatus;
}

- (void)setSystemName:(NSString *)systemName{
    _systemName = systemName;
}

- (void)setSystemVersion:(NSString *)systemVersion{
    _systemVersion = systemVersion;
}

- (void)setModel:(NSString *)model{
    _model = model;
}

- (void)setUniqueIdentifier:(NSUUID *)uniqueIdentifier{
    _uniqueIdentifier = uniqueIdentifier;
}

- (void)setName:(NSString *)name{
    _name = name;
}

- (void)setLocalizedModel:(NSString *)localizedModel{
    _localizedModel = localizedModel;
}

- (void)setAppToken:(NSString *)appToken{
    if (_appToken != appToken) {
        _appToken = appToken;
        [[NSUserDefaults standardUserDefaults] setObject:appToken forKey:@"appToken"];
    }
}

@end
